package com.kum.filter;

import com.alibaba.fastjson.JSON;
import com.kum.domain.AjaxResult;
import com.kum.domain.entity.LoginUser;
import com.kum.utils.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServerRequest;

import java.util.List;

/**
 * @version V1.0
 * @Package com.kum.filter
 * @auhter 枯木Kum
 * @date 2021/5/30-2:17 PM
 * <p>token过滤器,仅仅作为提前将token的载荷转为loginUser使用</p>
 */

@Component
public class TokenFilter implements GlobalFilter ,Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        if (null != token) {
            //token过期处理
            if (!JwtUtil.verity(token)) {
                response.setStatusCode(HttpStatus.OK);
                DataBuffer data = response.bufferFactory().wrap(AjaxResult.forbidden().toString().getBytes());
                response.writeWith(Mono.just(data));
                return response.setComplete();

            } else {
                LoginUser payload = JwtUtil.getPayload(token);
                System.out.println(payload);
            }

        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
